package com.util;

import java.lang.reflect.Method;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

//@Configuration：spring在解析该类时会识别标注@bean的方法执行
//@EnableCaching: 开启基于注解的缓存
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport{
	private volatile JedisConnectionFactory jedisConnectionFactory;
	private volatile RedisTemplate<String, String> redisTemplate;
	private volatile RedisCacheManager redisCacheManager;
 
	public RedisCacheConfig() {
		super();
	}
 
	/**
	 * 带参数的构造方法 初始化所有的成员变量
	 * 
	 * @param jedisConnectionFactory
	 * @param redisTemplate
	 * @param redisCacheManager
	 */
	public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate<String, String> redisTemplate,
			RedisCacheManager redisCacheManager) {
		this.jedisConnectionFactory = jedisConnectionFactory;
		this.redisTemplate = redisTemplate;
		this.redisCacheManager = redisCacheManager;
	}
 
	public JedisConnectionFactory getJedisConnecionFactory() {
		return jedisConnectionFactory;
	}
 
	public RedisTemplate<String, String> getRedisTemplate() {
		return redisTemplate;
	}
 
	public RedisCacheManager getRedisCacheManager() {
		return redisCacheManager;
	}
 
	//缓存数据时key生成策略	
	//target：当前被调用的对象、method：当前被调用的方法、objects：被调用方法的参数数组
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... objects) {
				StringBuilder sb = new StringBuilder();
				sb.append(method.getName());
				if(objects.length != 0){
					sb.append("_");
					for (Object obj : objects) {
						sb.append(obj.toString());
					}
				}
				return sb.toString();
			}
		};
	}

}
